<!DOCTYPE HTML>
<html>

<head>
    <meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=0">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>区域掩模</title>
    <style>
        html,
        body,
        #container {
            margin: 0;
            height: 100%;
            background: none !important;
        }

        /* 高德地图 LOGO 和 ....号 */
        .amap-logo, .amap-copyright {
            display: none !important;
        }

        .custom-content-marker {
            animation-duration: 3s;
            animation-name: slidein;
            animation-iteration-count: infinite;
        }

        .amap-info-content { 
            /* background-color: none; */
            /* background-image: url('../src/assets/images/ba-lin-you-qi/img5.png') !important;
            background-size: 100% 100%; */
            /* color: #fff !important; */
            background-color: rgba(#fff, .6);
        }
        
        @keyframes slidein {
            0% { top: -100px;}
            100% { top: 0px;}
        }

    </style>
</head>

<body onLoad="">
    <div id="container"></div>

    <script type="text/javascript">
        window._AMapSecurityConfig = {
            securityJsCode: '8a677569fcc6b5e98a2803cb1befce4f',
        }
    </script>

    <!-- 1.4.15 API -->
    <!-- <script
        src="https://webapi.amap.com/maps?v=1.4.15&key=161d326fcc4a717a0763eba4feb06551&plugin=Map3D,AMap.DistrictLayer,AMap.DistrictSearch">
    </script>

    <script src="https://webapi.amap.com/loca?v=1.4.15&key=161d326fcc4a717a0763eba4feb06551"></script>

    <script 
        language="javascript" 
        src="https://webapi.amap.com/maps?v=1.4.15&key=161d326fcc4a717a0763eba4feb06551&plugin=Map3D,AMap.DistrictSearch">
    </script>  -->

    <!-- 2.0 API --> 
    <script language="javascript"
        src="https://webapi.amap.com/maps?v=2.0&key=161d326fcc4a717a0763eba4feb06551&plugin=Map3D,AMap.DistrictLayer,AMap.DistrictSearch,AMap.Geocoder,AMap.Marker,AMap.Scale,AMap.ToolBar,AMap.GeoJSON,AMap.MapboxVectorTileLayer">
    </script>

    <script src="https://webapi.amap.com/loca?v=2.0&key=161d326fcc4a717a0763eba4feb06551"></script>
    <script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>

    <script language="javascript">
        var map = null
        var mapCenter = [118.671389, 43.521016]

        var geocoder = new AMap.Geocoder({
            city: "010", //城市设为北京，默认：“全国”
            radius: 1000 //范围，默认：500
        });

        // var marker = new AMap.Marker();

        var adCode = 150423;
        var depth = 2;

        var disProvince;

        var district = null;
        var polygons = [];

        // 区域掩模
        var opts = {
            subdistrict: 0,   // 返回下一级行政区
            level: 'district',
            extensions: 'all',  //返回行政区边界坐标组等具体信息
            showbiz: false,
            level: "city"
        };

        //实例化 DistrictSearch
        var district = new AMap.DistrictSearch(opts);

        district.search('巴林右旗', function (status, result) {
            var adCode = result.districtList[0].adcode
            var bounds = result.districtList[0].boundaries;
            var mask = []

            for (var i = 0; i < bounds.length; i += 1) {
                mask.push([bounds[i]])
            }

            map = new AMap.Map('container', {
                mask: mask,
                center: mapCenter,
                viewMode: '3D',
                labelzIndex: 130,
                pitch: 40,
                zoom: 8.7,
                terrain: true,
                cursor: 'pointer',
                rotation: -45,
                animateEnable: true,
                resizeEnable: true,
                layers: [
                    new AMap.TileLayer.RoadNet({
                        zIndex: 7
                    }),
                    // disCountry,
                    new AMap.TileLayer.Satellite()
                ],
            });


            // 添加 GeoJson 图层
            // ajax('./ba-lin-you-qi.json', function(err, geoJSON) {
            //     if (!err) {
            //         var geojson = new AMap.GeoJSON({
            //             geoJSON: geoJSON,
            //             // 还可以自定义getMarker和getPolyline
            //             getPolygon: function(geojson, lnglats) {
            //                 // 计算面积
            //                 var area = AMap.GeometryUtil.ringArea(lnglats[0])

            //                 return new AMap.Polygon({
            //                     path: lnglats,
            //                     fillOpacity: 1 - Math.sqrt(area / 8000000000),// 面积越大透明度越高
            //                     strokeColor: 'white',
            //                     fillColor: ''
            //                 });
            //             }
            //         });
            //         map.add(geojson);
            //         log.success('GeoJSON 数据加载完成')
            //     } else {
            //         log.error('GeoJSON 服务请求失败')
            //     }
            // })
            
            //添加高度面
            var object3Dlayer = new AMap.Object3DLayer({
                zIndex: 9
            });

            map.add(object3Dlayer)
            var height = -40000;
            var color = '#326791'; //rgba
            var wall = new AMap.Object3D.Wall({
                path: bounds,
                height: height,
                color: color
            });
            wall.transparent = true
            object3Dlayer.add(wall)

            const markerContent = '' +
            '<div class="custom-content-marker">' +
            '   <img src="../src/assets/images/user/user-avatar.png">' +
            '   <div class="close-btn" onclick="removeMarker()">X</div>' +
            '</div>';

            const position = new AMap.LngLat(118.671389, 43.521016); // Marker经纬度
            
            const marker = new AMap.Marker({
                position: position,
                content: markerContent, // 将 html 传给 content
                offset: new AMap.Pixel(-13, -30) // 以 icon 的 [center bottom] 为原点
            });
            // map.add(marker);

            //添加描边
            for (var i = 0; i < bounds.length; i += 1) {
                new AMap.Polyline({
                    path: bounds[i],
                    strokeColor: '#fff',
                    strokeWeight: 5,
                    map: map
                })
            }

            // 获取天气
            // GetWeather(name)

            // 划线行政区
            // initPro(result.districtList[0].adcode, 1);

            map.on('click', e => {
                clickMap(e)
                console.log('e : ', e);
            });
        })

        var userSendList = []
        var positionList = []

        

        // 接收 map.vue 传递的参数
        function getMessageFromParent(value) {
            let pointType = ''
            let userSendData = JSON.parse(value)
            userSendData.data = JSON.parse(userSendData.data)
            console.log('userSendData : ', userSendData);
            userSendList.push(userSendData)

            if (userSendData.data.fangYiYuan && userSendData.data.fangYiYuan.name && !userSendData.data.yiZhiList) {
                pointType = '防疫'
            } else if (userSendData.data.yiZhiList) {
                pointType = '医治'
            } else {
                pointType = '呼叫'
            }

            var position = new AMap.LngLat(userSendData.lon, userSendData.lat);

            showTip(position, pointType)

            // if (pointType == '防疫') {
            //     showfangYiPoint(position)
            // } else if (pointType == '医治') {
            //     showYiZhiPoint(position)
            // } else if (pointType == '呼叫') {
            //     showHuJiaoPoint(position)
            // }

            // positionList.push(position)

            // for (let i in positionList) {
            //     showTip(positionList[i], pointType)
            //     // showTip(positionList[i])
            // }
        } 

        // 显示 防疫 点
        function showfangYiPoint(val) {
           // 点标记显示内容，HTML要素字符串
           let fangYiMarkerContent = '' +
                '<div class="custom-content-marker">' +
                '   <img src="./ding-wei/img1.png">' +
                '</div>';

            let fangYiMarker = new AMap.Marker({
                position: val,
                // 将 html 传给 content
                content: fangYiMarkerContent,
                // 以 icon 的 [center bottom] 为原点
                offset: new AMap.Pixel(-13, -30)
            });

            fangYiMarker.on('click', val => {
                console.log('点击标记点 : ', val.target._position.lng, val.target._position.lat);
                console.log('标记点类型 : ', val.type)
                let lng = val.target._position.lng
                let lat = val.target._position.lat

                console.log('userSendList : ', userSendList);

                // 点击 point 显示 牧户/防疫员/兽医 提交的信息
                for (let i in userSendList) {
                    if (userSendList[i].lon == lng && userSendList[i].lat == lat) {
                        emitMessage(userSendList[i].data)
                    }
                }
            })

            map.add(fangYiMarker);
        }

        // 显示 医治 点
        function showYiZhiPoint(val) {
           // 点标记显示内容，HTML要素字符串
           let yiZhiMarkerContent = '' +
                '<div class="custom-content-marker">' +
                '   <img src="./ding-wei/img3.png">' +
                '</div>';

            let yiZhiMarker = new AMap.Marker({
                position: val,
                // 将 html 传给 content
                content: yiZhiMarkerContent,
                // 以 icon 的 [center bottom] 为原点
                offset: new AMap.Pixel(-13, -30)
            });

            yiZhiMarker.on('click', val => {
                console.log('点击标记点 : ', val.target._position.lng, val.target._position.lat);
                console.log('标记点类型 : ', val.type)
                let lng = val.target._position.lng
                let lat = val.target._position.lat

                console.log('userSendList : ', userSendList);

                // 点击 point 显示 牧户/防疫员/兽医 提交的信息
                for (let i in userSendList) {
                    if (userSendList[i].lon == lng && userSendList[i].lat == lat) {
                        emitMessage(userSendList[i].data)
                    }
                }
            })

            map.add(yiZhiMarker);
        }

         // 显示 呼叫 点
         function showHuJiaoPoint(val) {
           // 点标记显示内容，HTML要素字符串
           let huJiaoMarkerContent = '' +
                '<div class="custom-content-marker">' +
                '   <img src="./ding-wei/img3.png">' +
                '</div>';

            let huJiaoMarker = new AMap.Marker({
                position: val,
                // 将 html 传给 content
                content: huJiaoMarkerContent,
                // 以 icon 的 [center bottom] 为原点
                offset: new AMap.Pixel(-13, -30)
            });

            huJiaoMarker.on('click', val => {
                console.log('点击标记点 : ', val.target._position.lng, val.target._position.lat);
                console.log('标记点类型 : ', val.type)
                let lng = val.target._position.lng
                let lat = val.target._position.lat

                console.log('userSendList : ', userSendList);

                // 点击 point 显示 牧户/防疫员/兽医 提交的信息
                for (let i in userSendList) {
                    if (userSendList[i].lon == lng && userSendList[i].lat == lat) {
                        emitMessage(userSendList[i].data)
                    }
                }
            })

            map.add(huJiaoMarker);
        }

        // 显示 点标记
        function showTip(val, pointType) {
            console.log(pointType);
            var markerContent = ''
            if (pointType == '防疫') {
                // 点标记显示内容，HTML要素字符串
                markerContent = '' +
                    '<div class="custom-content-marker">' +
                    '   <img src="./ding-wei/img1.png">' +
                    '</div>';
            } else if (pointType == '医治') {
                // 点标记显示内容，HTML要素字符串
                markerContent = '' +
                '<div class="custom-content-marker">' +
                    '   <img src="./ding-wei/img3.png">' +
                    '</div>';
            } else if (pointType == '呼叫') {
                // 点标记显示内容，HTML要素字符串
                markerContent = '' +
                '<div class="custom-content-marker">' +
                    '   <img src="./ding-wei/img2.png">' +
                    '</div>';
            }

            // 点标记显示内容，HTML要素字符串
            // var markerContent = '' +
            //     '<div class="custom-content-marker">' +
            //     '   <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png">' +
            //     '</div>';

            var marker = new AMap.Marker({
                position: val,
                // 将 html 传给 content
                content: markerContent,
                // 以 icon 的 [center bottom] 为原点
                offset: new AMap.Pixel(-13, -30)
            });

            marker.on('click', val => {
                console.log('val : ', val);

                // ----------- map 2.0 (必须是 高德地图 2.0 版本才能点击 Marker 后获取到 Marker 的坐标) ------------ 
                // -------------------- map 1.4.15 点击 Marker 后获取到的是点击地图上的坐标，不是 Marker 的坐标
                console.log('点击标记点 : ', val.target._position.lon, val.target._position.lat);
                console.log('标记点类型 : ', val.type)

                let lng = val.target._position.lng
                let lat = val.target._position.lat

                console.log('userSendList : ', userSendList);

                for (let i in userSendList) {
                    if (userSendList[i].lon == lng && userSendList[i].lat == lat) {
                        emitMessage(userSendList[i].data)
                    }
                }
               
            })

            // 将 markers 添加到地图
            map.add(marker);
        }

        // 向 map.vue 页面发送信息
        function emitMessage(val) {
            window.parent.postMessage(val, '*');
        }

        // 鼠标单击事件
        function clickMap(e) {
            // 获取经纬度
            var lnglat = [e.lnglat.getLng(), e.lnglat.getLat()]
            console.log('当前经纬度 : ', lnglat);
            mapCenter = lnglat

            // 逆地理编码 -> 返回地址名称
            regeoCode(lnglat)

            // 显示行政区
            showDistrict(e.pixel)
        }

        // 点击 获取地理名称
        function regeoCode(val) {
            // map.add(marker);
            // marker.setPosition(val);

            // geocoder.getAddress(val, function (status, result) {
            //     if (status === 'complete' && result.regeocode) {
            //         var address = result.regeocode.formattedAddress;
            //         console.log('获取地址信息 : ', result.regeocode);
            //     } else {
            //         console.error('根据经纬度查询地址失败')
            //     }
            // });
        }

        function showIcon1(val) {
            let icon = '../assets/images/ding-wei/img1.png'
            return icon
        }

        function showVideo(val) {
            let baseUrl = 'http://dsj.dayaar.com.cn/pro/profile/'
            let videoPath = val[0]

            return baseUrl + videoPath
        }

        function showImg(val) {
            let baseUrl = 'http://dsj.dayaar.com.cn/pro/profile/'
            let imgPath = val[1]

            return baseUrl + imgPath
        }

        function drawBounds() {
            //加载行政区划插件
            if (!district) {
                //实例化DistrictSearch
                var opts = {
                    subdistrict: 0,   //获取边界不需要返回下级行政区
                    extensions: 'all',  //返回行政区边界坐标组等具体信息
                    level: 'district'  //查询行政级别为 市
                };
                district = new AMap.DistrictSearch(opts);
            }

            //行政区查询
            district.setLevel('district')
            district.search('索博日嘎镇', function (status, result) {
                map.remove(polygons)//清除上次结果
                polygons = [];
                var bounds = result.districtList[0].boundaries;
                if (bounds) {
                    for (var i = 0, l = bounds.length; i < l; i++) {
                        //生成行政区划polygon
                        var polygon = new AMap.Polygon({
                            strokeWeight: 1,
                            path: bounds[i],
                            fillOpacity: 0.4,
                            fillColor: '#80d8ff',
                            strokeColor: '#0091ea'
                        });
                        polygons.push(polygon);
                    }
                }
                map.add(polygons)
                map.setFitView(polygons);//视口自适应
            });
        }
        drawBounds();

        // 显示行政区
        function showDistrict(val) {
            var px = val;
            // 拾取所在位置的行政区
            var props = disWorld.getDistrictByContainerPos(px);

            if (props) {
                var SOC = props.SOC;
                if (SOC) {
                    // 重置行政区样式
                    disWorld.setStyles({
                        // 国境线
                        //nation-stroke': nationStroke,
                        // 海岸线
                        //'coastline-stroke': '',
                        'fill': function (props) {
                            return props.SOC == SOC ? nationFill : 'white';
                        }
                    });
                    updateInfo(props);
                }
            }
        }

        function initPro(code) {
            adCode = 150423;
            depth = 2;

            disProvince && disProvince.setMap(null);

            disProvince = new AMap.DistrictLayer.Province({
                zIndex: 12,
                adcode: [code],
                depth: 2,
                styles: {
                    'fill': function (properties) {
                        // properties为可用于做样式映射的字段，包含
                        // NAME_CHN:中文名称
                        // adcode_pro
                        // adcode_cit
                        // adcode
                        var adcode = properties.adcode;
                        return getColorByAdcode(adcode);
                    },
                    'province-stroke': 'cornflowerblue',
                    'city-stroke': 'white', // 中国地级市边界
                    'county-stroke': 'rgba(255,255,255,0.5)' // 中国区县边界
                }
            });

            disProvince.setMap(map);
        }


        // 颜色辅助方法
        var colors = {};
        var getColorByAdcode = function (adcode) {
            if (!colors[adcode]) {
                var gb = Math.random() * 155 + 50;
                colors[adcode] = 'rgb(' + gb + ',' + gb + ',255)';
            }

            return colors[adcode];
        };

        initPro(150423);




















        function rotate() {
            window.requestAnimationFrame(() => {
                //if (mapAnimateControl == true) {
                map.setRotation((map.getRotation() + 0.02) % 360);
                // }
                rotate()
            })
        }

        function GetWeather(name) {
            AMap.plugin("AMap.Weather", function () {
                var weather = new AMap.Weather();
                weather.getLive(name, function (err, data) {
                    if (!err) {
                        var html =
                            "" +
                            "" +
                            data.weather +
                            "<br/>" +
                            "" +
                            data.windDirection +
                            "风" +
                            "<b>" +
                            data.temperature +
                            "℃ </b>";

                        $("#Weather").html(html);
                    }
                });
            });
        }

        AMap.plugin("AMap.Weather", function () {
            var weather = new AMap.Weather();
            weather.getLive(name, function (err, data) {
                if (!err) {
                    var html =
                        "" +
                        "" +
                        data.weather +
                        "<br/>" +
                        "" +
                        data.windDirection +
                        "风" +
                        "<b>" +
                        data.temperature +
                        "℃ </b>";

                    $("#Weather").html(html);
                }
            });
        });


        function getDate() {
            var today = new Date();
            var date =
                twoDigits(today.getMonth() + 1) + "/" + twoDigits(today.getDate()) + "";
            var week = " 星期" + "日一二三四五六 ".charAt(today.getDay());
            var time = twoDigits(today.getHours()) + ":" + twoDigits(today.getMinutes());
            $(".time").html(time);
        }

        function twoDigits(val) {
            if (val < 10) return "0" + val;
            return val;
        }

        // $(function () {
        //     setInterval(getDate, 1000);
        // });

        function settab(tab) {
            $(".header-bar a").each(function (i, elem) {
                //一参:下标
                $(elem).removeClass("active");

                if (tab == i) {
                    $(elem).addClass("active");
                }
            });
            type = tab;
            getAreaAjax(); //初始化
        }








    </script>
</body>

</html>